const cloud = require('wx-server-sdk')

cloud.init()

const db = cloud.database({
  env: 'gtss-2b1812'
})
exports.main = async(event, context) => {
  if (event.userType == 1) {
    try {
      const oldPas = await db.collection('Student').doc(event.userId).field({
        stuPas: true
      }).get()
      if (event.oldPas == oldPas.data.stuPas) {
        await db.collection('Student').doc(event.userId).update({
          data: {
            stuPas: event.newPas
          }
        })
        return {
          result: 1
        }
      } else {
        return {
          result: 0
        }
      }
    } catch (e) {
      return {
        result: 2
      }
    }
  } else if (event.userType == 2) {
    try {
      const oldPas = await db.collection('Teacher').doc(event.userId).field({
        teaPas: true
      }).get()
      if (event.oldPas == oldPas.data.teaPas) {
        await db.collection('Teacher').doc(event.userId).update({
          data: {
            teaPas: event.newPas
          }
        })
        return {
          result: 1
        }
      } else {
        return {
          result: 0
        }
      }
    } catch (e) {
      return {
        result: 2
      }
    }
  } else if (event.userType == 3) {
    try {
      const oldPas = await db.collection('Administrator').doc(event.userId).field({
        admPas: true
      }).get()
      if (event.oldPas == oldPas.data.admPas) {
        await db.collection('Administrator').doc(event.userId).update({
          data: {
            admPas: event.newPas
          }
        })
        return {
          result: 1
        }
      } else {
        return {
          result: 0
        }
      }
    } catch (e) {
      return {
        result: 2
      }
    }
  }
}